import React, { Component } from 'react';
import { get_login } from '../utils/api'
import { Toast } from 'antd-mobile'

class Login extends Component {

    state = {
        phone: "",
        pass: ""
    }


    //跳转到注册页面
    handleRegister() {
        this.props.history.push({ pathname: '/register' })
    }


    handleChange(e) {
        this.setState({
            [e.target.name]: e.target.value
        })
    }

    login() {
        if (this.state === '') {
            Toast.show({ icon: 'fail', content: '不能为空' })
        } else {
            get_login(this.state).then((res) => {
                if (res.data.code === 200) {
                    //登陆成功，保存touken到本地
                    localStorage.setItem("token", res.data.token)
                    // //登陆成功，保存userinfo到本地
                    localStorage.setItem("userinfo", JSON.stringify(res.data.userinfo))
                    //登陆成功后，跳转到首页
                    this.props.history.push({ pathname: "/index" })
                    Toast.show({ icon: 'success', content: res.data.msg })
                }
            })
        }
    }


    render() {
        return (
            <div className='login'>
                <div className="Box">
                    <div className="odiv user">
                        <input type="text" name='phone' value={this.state.phone} onChange={(e) => { this.handleChange(e) }} placeholder="请输入用户名" />
                    </div>
                    <div className="odiv pass">
                        <input type="password" name='pass' value={this.state.pass} onChange={(e) => { this.handleChange(e) }} placeholder="请输入密码" />
                    </div>
                    <div className="odiv btn">
                        <input type="button" value="登录" onClick={() => { this.login() }} />
                    </div>
                    <div className='odiv reg'><span onClick={() => { this.handleRegister() }}>注册</span></div>
                </div>
            </div>
        );
    }
}

export default Login;